﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CaptchaGen;
using HPIT.RentHouse.Common;
using HPIT.RentHouse.IService;
using HPIT.RentHouse.DTO;
using System.Web.Security;

namespace HPIT.RentHouse.Admin.Controllers
{
    public class HomeController : Controller
    {
        //反转注入
        private ILogin _login;
        public HomeController(ILogin Login)
        { 
           _login = Login;  
        }

        public ActionResult NoPermission()
        {
            return View();
        }
        /// <summary>
        /// 默认页面(视图)
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 登录页面(视图)
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 实现点击刷新验证码(方法)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetVerCode()
        {
            //生成验证码文字--调用CommonHelper中随机生成验证码文字的方法
            string code = CommonHelper.CreateVerifyCode(4);
            //使用TempData临时存储验证码文字  (页面刷新验证码会失效)
            TempData["VerCode"] = code;
            //使用CaptchaGen中自带的方法ImageFactory实现验证码生成
            var src = ImageFactory.GenerateImage(code,60,100,15,6);
            //返回文件(生成的验证码图片)
            return File(src,"image/jpeg");
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SubmitLogin(LoginDTO dto)
        {
            if (TempData["VerCode"]==null)
            {
                return Json(new AjaxResult(ResultState.Error, "验证码已失效"));
            }
            else
            {
                string code = TempData["VerCode"].ToString();
                if (code!=dto.VerCode)
                {
                    return Json(new AjaxResult(ResultState.Error, "验证码输入有误"));
                }
                else
                {
                    var result = _login.Login(dto);
                    return Json(result);
                }
            }
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public ActionResult ExitLogin()
        {
            //清除用户缓存
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
        }
    }
}